//
//  NetworkViewController.swift
//  AKTest
//
//  Created by ZDST2018 on 2021/8/25.
//

import UIKit
import Alamofire
import RxDataSources


class NetworkViewController: UIViewController {
    
    @IBOutlet weak var searchTF: UITextField!
    @IBOutlet weak var porjectTabView: UITableView!
    lazy var bag = DisposeBag.init()
    
    typealias ScetionTableModle = SectionModel<String, RepositoriesModel>
    var dataSource = RxTableViewSectionedReloadDataSource<ScetionTableModle>.init { source, tabV, index, item in
        let cell: GitHubCell = tabV.dequeueReusableCell(withIdentifier: "cellID") as! GitHubCell
        cell.name.text = item.name
        return cell
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        porjectTabView.register(UINib.init(nibName: "GitHubCell", bundle: nil), forCellReuseIdentifier: "cellID")
        searchTF.rx.text.throttle(.milliseconds(2000), scheduler: MainScheduler.init()).filter({ (text: String?) -> Bool in
            if let str = text, str.count < 3{
                return false
            }
            return true
        }).flatMap({[weak self] (str : String?) in
            self!.network(repositoryName: str!)
        }).bind(to: self.porjectTabView.rx.items(dataSource: dataSource)).disposed(by: bag)
        
        
        //展示1组数据
//        porjectList.register(UINib.init(nibName: "GitHubCell", bundle: nil), forCellReuseIdentifier: "cellID")
//        searchTF.rx.text.throttle(.milliseconds(2000), scheduler: MainScheduler.init()).filter({ (text: String?) -> Bool in
//            if let str = text, str.count < 3{
//                return false
//            }
//            return true
//        }).flatMap({[weak self] (str : String?) in
//            self!.network(repositoryName: str!)
//        }).bind(to: porjectList.rx.items(cellIdentifier: "cellID", cellType: GitHubCell.self)){ index, model, cell in
//            cell.name.text = model.name
//        }.disposed(by: bag)
        
    }
    
}

extension NetworkViewController{
    

    
    func network(repositoryName: String) -> Observable<Array<ScetionTableModle>> {
        
        return Observable.create { (obs : AnyObserver<Array<ScetionTableModle>>) -> Disposable in
            let url = "https://api.github.com/search/repositories"
            AlamoFireTool.get(url: url, parameters: ["q":repositoryName,"stars": "2000"]).responseJSON { (dataRes: DataResponse<Any>) in
                switch dataRes.result {
                case .success(let json):
                    let dict = json as? [String: Any]
                    let total_count = dict?["total_count"] as! Int

                    guard total_count != 0 else {
                        print("没有这个框架")
                        return
                    }
                    let arr = dict?["items"] as? [Dictionary<String, Any>]
                    let moArr = self.createGithubSectionModel(repArr: arr?.kj.modelArray(RepositoriesModel.self) ?? [])
                    obs.onNext(moArr)
                case .failure(let error):
                    print(error)
                }
            }
            return Disposables.create()
        }
    }
    //分组
    private func createGithubSectionModel(repArr: [RepositoriesModel]) ->[ScetionTableModle] {
        
        var items: [RepositoriesModel] = []
        var stm: [ScetionTableModle] = []
        
        if repArr.count < 10 {
            stm.append(ScetionTableModle.init(model: "1 - 10", items: repArr))
        }else{
            for i in 1...repArr.count {
                items.append(repArr[i-1])
                if i/10 != 0 && i % 10 == 0 {
                    stm.append(ScetionTableModle.init(model: "\(i-10) - \(i)", items: items))
                    items = []
                }
            }
        }
        return stm
    }
}


struct RepositoriesModel: Convertible, CustomStringConvertible {
    var avatar_url: String = ""
    var name: String = ""
    init() {}
    func kj_modelKey(from property: Property) -> ModelPropertyKey {
        switch property.name {
        case "avatar_url":
            return "owner.avatar_url"
        default:
            return property.name
        }
    }
    
    var description: String{
        get{
            self.kj.JSONString()
        }
    }
}
